#!/usr/bin/env python3
"""
简单的测试服务器
"""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional
from datetime import datetime
from decimal import Decimal

app = FastAPI(title="GSignal Test Server", version="0.1.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 简单的数据存储
signal_collections = []
devices = []
next_id = 1

class SignalCollectionIn(BaseModel):
    device_id: str
    signal_strength: int
    latitude: float
    longitude: float
    altitude: Optional[float] = None
    accuracy: Optional[float] = None
    network_type: Optional[str] = None
    operator_name: Optional[str] = None
    cell_id: Optional[str] = None
    lac: Optional[str] = None
    mcc: Optional[str] = None
    mnc: Optional[str] = None
    rsrp: Optional[int] = None
    rsrq: Optional[float] = None
    rssi: Optional[int] = None
    snr: Optional[float] = None
    collected_at: datetime

class DeviceInfoIn(BaseModel):
    device_id: str
    device_name: Optional[str] = None
    device_model: Optional[str] = None
    os_version: Optional[str] = None
    app_version: Optional[str] = None

@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "timestamp": datetime.utcnow(),
        "database": "memory_storage"
    }

@app.post("/signal/collect")
async def collect_signal(signal_data: SignalCollectionIn):
    """采集4G信号数据"""
    global next_id
    
    record = {
        "id": next_id,
        **signal_data.dict(),
        "uploaded_at": datetime.utcnow(),
        "created_at": datetime.utcnow(),
    }
    
    signal_collections.append(record)
    next_id += 1
    
    return record

@app.get("/signal/collections")
async def get_signal_collections(
    device_id: Optional[str] = None,
    limit: int = 100,
    offset: int = 0
):
    """获取信号采集记录列表"""
    records = signal_collections.copy()
    
    if device_id:
        records = [r for r in records if r.get("device_id") == device_id]
    
    # 按时间倒序排列
    records.sort(key=lambda x: x["collected_at"], reverse=True)
    
    return records[offset:offset + limit]

@app.get("/signal/statistics/{device_id}")
async def get_signal_statistics(device_id: str):
    """获取设备信号统计信息"""
    device_records = [r for r in signal_collections if r.get("device_id") == device_id]
    
    if not device_records:
        raise HTTPException(status_code=404, detail="未找到该设备的统计信息")
    
    signal_strengths = [r["signal_strength"] for r in device_records]
    collected_times = [r["collected_at"] for r in device_records]
    
    return {
        "device_id": device_id,
        "total_collections": len(device_records),
        "avg_signal_strength": sum(signal_strengths) / len(signal_strengths),
        "min_signal_strength": min(signal_strengths),
        "max_signal_strength": max(signal_strengths),
        "first_collection": min(collected_times),
        "last_collection": max(collected_times),
        "collection_days": len(set(d.date() for d in collected_times)),
    }

@app.post("/device/register")
async def register_device(device_info: DeviceInfoIn):
    """注册设备信息"""
    global next_id
    
    device_id = device_info.device_id
    
    # 检查设备是否已存在
    existing_device = next((d for d in devices if d["device_id"] == device_id), None)
    
    if existing_device:
        # 更新现有设备
        existing_device.update(device_info.dict())
        existing_device["last_seen"] = datetime.utcnow()
        existing_device["is_active"] = True
        existing_device["updated_at"] = datetime.utcnow()
        return existing_device
    else:
        # 创建新设备
        new_device = {
            "id": next_id,
            **device_info.dict(),
            "last_seen": datetime.utcnow(),
            "is_active": True,
            "created_at": datetime.utcnow(),
            "updated_at": datetime.utcnow(),
        }
        devices.append(new_device)
        next_id += 1
        return new_device

if __name__ == "__main__":
    import uvicorn
    print("🚀 启动测试服务器...")
    uvicorn.run(app, host="0.0.0.0", port=8886)